package br.sed.theenemy.presentation.servlets;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.sed.theenemy.business.exception.DBException;
import br.sed.theenemy.business.services.Services;
import br.sed.theenemy.business.utils.Utils;
import br.sed.theenemy.presentation.EnemyErrorConstants;
import br.sed.theenemy.presentation.action.json.exception.ExpectedException;
import br.sed.theenemy.presentation.action.json.exception.IdentifiedException;
import br.sed.theenemy.presentation.servlets.json.JSONBaseServlet;


/**
 * 
 * @author Julio CB
 * @email jcbjulio@gmail.com
 * 
 */
@WebServlet("/countByName")
public class countByNameServlet extends JSONBaseServlet {

	private static final long serialVersionUID = -5120099177751980303L;

	@Override
	protected Object executeJSON(HttpServletRequest request,
			HttpServletResponse response) throws ExpectedException,
			IdentifiedException {
		Services services = Services.getInstance();
		
		List<String> errors =  new ArrayList<String>();
		errors = validate(request);
		if (errors.size()!=0){
			throw new ExpectedException(EnemyErrorConstants.MISSING_PARAM, errors);
		}
		String name = request.getParameter("name");
		
		Integer userNumber = null;
		try {
			 userNumber = services.countUserByPieceOfName(name);
		} catch (DBException e) {
			throw new ExpectedException(EnemyErrorConstants.DB_EXCEPTION);
		} 

		return userNumber;
	}
	private List<String> validate(HttpServletRequest request){
		List<String> errors = new ArrayList<String>();
		if(Utils.isNullOrEmptyOrNotLetter(request.getParameter("name"))){
			errors.add("Missing Name");
		}
		return errors;
	}
}
